package com.ray;

import java.sql.*;

public class JDBCByOffical
{
    public static void main(String[] args)
    {
        try
        {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        }
        catch (Exception ex)
        {
            // handle the error
        }
        Connection conn = null;
        try
        {
            conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=root&password=");

            // Do something with the Connection

        }
        catch (SQLException ex)
        {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

        // assume that conn is an already created JDBC connection (see previous examples)

        Statement stmt = null;
        ResultSet rs = null;

        try
        {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM USER");

            // or alternatively, if you don't know ahead of time that
            // the query will be a SELECT...
            // 这部分是使用另外一种sql执行方法，是重复执行，因此注释掉。
            // if (stmt.execute("SELECT foo FROM bar"))
            // {
            //     rs = stmt.getResultSet();
            // }

            // Now do something with the ResultSet ....
            // 输出相应的数据
            while (rs.next()){
                System.out.println(rs.getString("NAME"));
            }
        }
        catch (SQLException ex)
        {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        finally
        {
            // it is a good idea to release
            // resources in a finally{} block
            // in reverse-order of their creation
            // if they are no-longer needed

            if (rs != null)
            {
                try
                {
                    rs.close();
                }
                catch (SQLException sqlEx)
                {
                }

                rs = null;
            }

            if (stmt != null)
            {
                try
                {
                    stmt.close();
                }
                catch (SQLException sqlEx)
                {
                }

                stmt = null;
            }
        }

        if (conn != null)
        {

            try
            {
                conn.close();
            }
            catch (SQLException e)
            {
                throw new RuntimeException(e);
            }
        }
    }
}
